
package Type_1_arr.title1_P704;

//p704 二分查找
public class P704BinarySearch {


    public static int search(int[] nums, int target) {

        int left = 0;
        int right = nums.length - 1;  //左闭右闭

        while (left <= right) {
            int midIndex = (left + right) / 2;
            if (target > nums[midIndex]) {
                left = midIndex + 1;
            } else if (target < nums[midIndex]) {
                right = midIndex - 1;
            } else {
                return midIndex;
            }
        }
        return -1;
    }

    public static void main(String[] args) {


        int[] nums = {-1, 0, 3, 5, 9, 12};
        int num = search(nums, 9);
        System.out.println("元素所在索引" + num);
    }
}